var jWidget;
jWidget || (function()
{
   var widgetLoggerEnabled = true;
   var widgetLoggerLevels = {DEBUG:10, INFO:20, WARN:30, ERROR:40};
   var widgetLoggerLevel = widgetLoggerLevels.DEBUG;

   var _jWidget = {
      log: function()
      {/* use the conlose of the browser to log if it is present. */
         if (widgetLoggerEnabled && typeof window.console !== 'undefined')
         {
            jWidget.log = function(msg)
            {
               window.console.debug(msg);
            };
         }
      },
      debug: function(msg)
      {
         if (widgetLoggerLevel <= widgetLoggerLevels.DEBUG) { jWidget.log("DEBUG: " + msg); };
      },
      info: function(msg)
      {
         if (widgetLoggerLevel <= widgetLoggerLevels.INFO) { jWidget.log("INFO: " + msg); };
      },
      warn: function(msg)
      {
         if (widgetLoggerLevel <= widgetLoggerLevels.WARN) { jWidget.log("WARN: " + msg); };
      },
      error: function(msg)
      {
         if (widgetLoggerLevel <= widgetLoggerLevels.ERROR) { jWidget.log("ERROR: " + msg); };
         alert(msg);
      },
      /*
       Loads the specified scripts into the browser it expects an object or an array of these objects as defined below:
       {
       url: [Url of the javascript],
       name: [Name for the library. Optional],
       functionToCheck: [A function from the script to be loaded. This function is used to check if script is fully loaded],
       callback: [function to call when script is loaded. Optional]
       version: [Version of the script. Optional],
       getVersionFunction: [A function or variable from the scripts that returns the version of the script. Optional]
       }

       or
       [{
       url: [URL1],
       functionToCheck: [function1],
       callback: [initScript1]
       },
       {
       url: [URL2],
       functionToCheck: [function2],
       callback: [initScript2]
       }]

       */
      loadScripts: function(scriptsToLoad)
      {
         jWidget.debug("start loadin");
         // check if scriptsToLoad is an array if not we asume it's a correct object
         if (scriptsToLoad.length === undefined)
         {
            jWidget.loadScript(scriptsToLoad);
         }
         else if (scriptsToLoad.length == 1)
         {
            jWidget.loadScript(scriptsToLoad[0]);
         }
         else
         {
            var lastScript = scriptsToLoad[scriptsToLoad.length-1];
            var previousScripts = scriptsToLoad.slice(0, scriptsToLoad.length-1);
            jWidget.loadScript(lastScript, jWidget.loadScripts(previousScripts));
         }
      },
      /*
       Loads the scriptURL into the browser. It expects an object in the form of:
       {
       url: [Url of the javascript],
       name: [Name for the library. Optional],
       functionToCheck: [A function from the script to be loaded. This function is used to check if script is fully loaded],
       callback: [function to call when script is loaded. Optional]
       version: [Version of the script. Optional],
       getVersionFunction: [A function or variable from the scripts that returns the version of the script. Optional]
       }
       */
      loadScript: function(scriptToLoad, executeAfterLoaded)
      {
         jWidget.debug("dynamically loading " + scriptToLoad.url);
         if (eval("typeof " + scriptToLoad.functionToCheck + " == 'undefined'"))
         {
            var script = document.createElement('script');
            script.setAttribute("type", "text/javascript");
            script.setAttribute("src", scriptToLoad.url);
            if (typeof script != "undefined")
            {
               document.getElementsByTagName("head")[0].appendChild(script);
            }
            jWidget.checkScriptLoaded(scriptToLoad.url, scriptToLoad.functionToCheck, scriptToLoad.callback, 0, executeAfterLoaded); // wait until jQuery loads before using it.
            jWidget.info("script loaded: " + scriptToLoad.url);
         }
         else
         {
            jWidget.log("script was allready loaded: " + scriptToLoad.url + "(name=" + scriptToLoad.name + ")");
            var scriptIgnoreProperty = "ignoreAllScriptChecks";
            if (scriptToLoad.name !== undefined)
            {
               scriptIgnoreProperty = "ignore" + scriptToLoad.name + "Check";
               jWidget.debug("setting ignore property to: " + scriptIgnoreProperty);
            }
            jWidget.log("scriptIgnoreProperty now: " + scriptIgnoreProperty);
            // alert a message if script was already loaded and not explicitly ignored.
            if (jWidget.getScriptParamValue("ignoreAllScriptChecks") === undefined && jWidget.getScriptParamValue(scriptIgnoreProperty) === undefined)
            {
               jWidget.scriptAllreadyLoaded(scriptToLoad, scriptIgnoreProperty);
            }
         }

      },
      /*
       Checks if a function is present (loaded) in the browser. It checks
       */
      checkScriptLoaded: function(scriptURL, functionToCheck, callbackFunction, time_elapsed, executeAfterLoaded)
      {
         if (functionToCheck === undefined)
         {
            jWidget.error("You must specify a function to check for the script: "+scriptURL + ". This function is used to be sure the script is loaded.");
         }
         else
         {
            jWidget.debug("checking for " + functionToCheck + ", time elapsed=" + time_elapsed);
            //   log("typeof eval(functionNameToCheck)= "+ typeof eval(functionNameToCheck));
            // Continually polls to see if jQuery is loaded.
            if (eval("typeof " + functionToCheck + " == 'undefined'"))
            //         if (typeof jQuery == "undefined")
            { // if jQuery isn't loaded yet...
               if (time_elapsed <= 5000)
               { // and we havn't given up trying...
                  jWidget.debug("setting timeout");
                  var callbackFuctionEscaped = callbackFunction.replace(/'/g, "\\'");
                  setTimeout("jWidget.checkScriptLoaded('" + scriptURL + "','" + functionToCheck + "','" + callbackFuctionEscaped + "'," + (time_elapsed + 200) + ", " + executeAfterLoaded + ")", 200); // set a timer to check again in 200 ms.
                  jWidget.debug("timeout set");
               }
               else
               {
                  jWidget.error("Timed out while loading " + scriptURL);
               }
            }
            else
            {
               jWidget.debug("calling callback function: " +callbackFunction );
               if (callbackFunction != 'undefined' && callbackFunction.length > 0)
               {
                  var functionToCall = callbackFunction;
                  if (functionToCall.replace(/\(.*\)$/i, "") == functionToCall)
                  {
                     // no brackets found add them
                     functionToCall += "()";
                  }
                  eval(functionToCall);
               }
               if (typeof executeAfterLoaded == 'function')
               {
                  executeAfterLoaded();
               }
               // code to run after jQuery is loaded!
            }
         }
      },

      scriptAllreadyLoaded: function(script, scriptIgnoreProperty)
      {
         var scripteNameForMessage = script.url;
         if (script.name !== undefined)
         {
            scripteNameForMessage = script.name;
         }
         if (script.getVersionFunction === undefined || script.version === undefined)
         {
            alert("jWidget tries to load the script " + scripteNameForMessage + ", but it (or and other version) is already loaded. " +
                  "\n\nIf you want to ignore this check add the requestParam '" + scriptIgnoreProperty + "' to the src of the jWidget javascript ");
         }
         else
         {
            var versionOfScriptLoaded = eval(script.getVersionFunction);
            var versionOfScriptLoadedToInt = versionOfScriptLoaded.replace(".", "");
            var versionToInt = script.version.replace(".", "");

            if (versionOfScriptLoadedToInt < versionToInt)
            {
               alert("We found an older version of the " + scripteNameForMessage + " library then jWidget requires. \nWe found '" +
                     scripteNameForMessage + "-" + versionOfScriptLoaded +
                     "' already loaded but we need a newer version '" + scripteNameForMessage + "-" + script.version +
                     "'. \njWidget automatically loads the " + scripteNameForMessage + "-" + script.version + " library if no " + scripteNameForMessage + " library was found." +
                     "\n\nIf you want to ignore this check add the requestParam '" + scriptIgnoreProperty + "' to the src of the jWidget javascript ");
            }
            else if (versionOfScriptLoadedToInt > versionToInt)
            {
               alert("You have a newer version of the " + scripteNameForMessage + " library loaded  (" + scripteNameForMessage + "-" + versionOfScriptLoaded +
                     "), we tested with an older version (" + scripteNameForMessage + "-" +
                     script.version + ") but the widget should probably run just fine." +
                     "\n If you want to ignore this check add the requestParam '" + scriptIgnoreProperty + "' to the src of the javascript ");
            }
         }

      },
      /*
       Returns the domain from where this widget script it loaded.
       */
      getHostingDomain: function ()
      {
         var hostingDomain = "";
         var scripts = document.getElementsByTagName("script");
         for (var i = 0; i < scripts.length; i++)
         {
            javascriptURL = scripts[i].getAttribute("src");
            if (javascriptURL.indexOf("insertWidget") != -1)
            {
               if (javascriptURL.indexOf("http://") != -1)
               {
                  var startOfRequestPath = javascriptURL.indexOf("/", "http://".length);
                  hostingDomain = javascriptURL.substring(0, startOfRequestPath);
               }
            }
         }
         return hostingDomain;
      },
      /*
       Returns the parameters after the script url of this javascript.
       */
      getScriptParamString: function ()
      {
         var scriptParams = "";
         var scripts = document.getElementsByTagName("script");
         for (var i = 0; i < scripts.length; i++)
         {
            javascriptURL = scripts[i].getAttribute("src");
            if (javascriptURL.indexOf("insertWidget") != -1 && javascriptURL.indexOf("http://") != -1 && javascriptURL.indexOf("?") != -1)
            {
               scriptParams = javascriptURL.substr(javascriptURL.indexOf("?") + 1); // get everything after the question mark. (+1 to ignore the question mark)
            }
         }
         return scriptParams;
      },
      getScriptParamValue: function(paramName)
      {
         var paramString = jWidget.getScriptParamString();
         jWidget.debug("checking for " + paramName + " in " + paramString);
         var indexOfParamName = paramString.indexOf(paramName);
         if (indexOfParamName == -1)
         {
            jWidget.debug("paramString = " + paramName + " not found.");
            return undefined;
         }
         else
         {
            var startIndex = paramString.indexOf("=", indexOfParamName) + 1; // don't include the =-character
            if (startIndex === 0) // check agains zero cause we added 1 remember :-)
            {
               startIndex = indexOfParamName + paramName.length;
            }
            var endIndex = paramString.indexOf("&", indexOfParamName);
            if (endIndex == -1)
            {
               endIndex = paramString.length;
            }
            var paramValue = paramString.substring(startIndex, endIndex);
            jWidget.debug("paramString = " + paramName + " found, value =" + paramValue);
            return paramValue;
         }
      }
   };

   jWidget = _jWidget;
})();


jWidget.log("log initialized");

var jQueryVersion = "1.4.2";
jWidget.loadScripts([
   {
      name:"jQuery",
      url:"http://ajax.googleapis.com/ajax/libs/jquery/" + jQueryVersion + "/jquery.min.js",
      functionToCheck:"jQuery",
      callback:"jQueryLoaded()",
      version:jQueryVersion,
      getVersionFunction:"jQuery.fn.jquery"
   },
   {
      name:"ecWidget",
      url:jWidget.getHostingDomain() + "/content/widget/js/ecWidget.js",
      functionToCheck:"ecWidget",
      callback:"ecWidgetLoaded()",
      version:"0.1",
      getVersionFunction:"ecWidget.version"
   }
]);

function jQueryLoaded()
{
   jWidget.info("joepie jQuery." + jQuery.fn.jquery + " is ingeladen");
   jQuery.noConflict();
}

function ecWidgetLoaded()
{
   jWidget.info("joepie ecWidget." + ecWidget.fn.version + " is ingeladen");
   ecWidget.init({host:jWidget.getHostingDomain()});
}
